<?php


namespace App\Service\client;


use App\Common\RedisUtils;
use App\Common\Res;
use App\Common\SendMsgUtils;
use App\Common\StringUtils;
use App\Constants\ConstCode;
use App\Constants\ErrorCode;
use App\Model\form\MessageTalkTrait;
use App\Model\form\WeworkAccountTrait;
use App\Model\form\WeworkFriendTrait;
use App\Model\TaskMobile;
use App\Request\client\CallBackRequest;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class callBackService
{
    use StringUtils, Res, RedisUtils, SendMsgUtils, MessageTalkTrait, WeworkFriendTrait, WeworkAccountTrait;

    /**
     *服务端发送消息给好友之后的回调
     * @param array $params
     * @return array
     */
    public function appMessageToFriend($fd, array $params): array
    {
        ApplicationContext::getContainer()->get(CallBackRequest::class)->validated($params['data'], __FUNCTION__);
        $params_data = $params['data'];
        if ($params['result'] == 1) {
            Db::beginTransaction();
            try {
                /*根据token查询redis是否存在数据*/
                $token = trim($params['token']);
                $deviceInfo = $this->hGet($this->hKey, $token);
                if (empty($deviceInfo)) {
                    return $this->Error(ErrorCode::ERROR, '设备登录信息错误');
                }
                $messageKey = $this->zScore('messageKey', $params_data['key']);
                if ($messageKey !== null) {
                    $message = $this->hGet('message', $params_data['key']);
                    if (!empty($message)) {
                        $messageArr = json_decode($message, true);
                        $messageInfo = $this->getMessageInfo(['id' => $messageArr['id']]);
                        $messageInfo->is_send = 1;
                        $result = $messageInfo->save();
                        /*删除redis数据*/
                        if ($result) {
                            $count = $this->zRem('messageKey', $params_data['key']);
                            if ($count > 0) {
                                $this->hDel('message', $params_data['key']);
                            }
                        }
                    }
                    Db::commit();
                    return $this->Success('用户信息回调处理成功');
                } else {
                    Db::commit();
                    return $this->Error(ErrorCode::ERROR, '用户信息键值为空');
                }
            } catch (\Throwable $ex) {
                Db::rollBack();
                return $this->Error(ErrorCode::ERROR, '用户信息回调处理失败' . $ex->getMessage());
            }
        } else {
            /*运营号被删除好友*/
            if (!empty($params_data['friend_status'])) {
                if ($params_data['friend_status'] != 1) {
                    if (empty($params_data['mobile']) && empty($params_data['nickname']))
                        return $this->Error(ErrorCode::ERROR, '好友手机号码和昵称不能同时为空');
                    /*根据token查询redis是否存在数据*/
                    $token = trim($params['token']);
                    $deviceInfo = $this->hGet($this->hKey, $token);
                    if (empty($deviceInfo)) {
                        return $this->Error(ErrorCode::ERROR, '设备登录信息错误');
                    }
                    $deviceArr = json_decode($deviceInfo, true);
                    Db::beginTransaction();
                    try {
                        $account = $this->getWeworkAccount(['marketUserId' => $deviceArr['marketUserId']]);
                        if (!empty($account)) {
                            $where['account_id'] = $account['id'];
                            if (!empty($params_data['mobile'])) {
                                $where['mobile'] = $params_data['mobile'];
                            } else {
                                $where['nickname'] = $params_data['nickname'];
                            }
                            $friend = $this->getWeworkFriendInfo($where);
                            if (!empty($friend)) {
                                $friend->status = intval($params_data['friend_status']);
                                $friend->save();
                            }
                            $this->updateAllUserMessage(['userId' => $friend['userId'], 'account_id' => $friend['account_id']], ['status' => 0]);
                            $messageKey = $this->zScore('messageKey', $params_data['key']);
                            if ($messageKey !== null) {
                                $this->zRem('messageKey', $params_data['key']);
                                $message = $this->hGet('message', $params_data['key']);
                                if (!empty($message)) {
                                    $this->hDel('message', $params_data['key']);
                                }
                            }
                        }
                        Db::commit();
                        return $this->Success('好友消息删除处理成功');
                    } catch (\Throwable $ex) {
                        Db::rollBack();
                        return $this->Error(ErrorCode::ERROR, '好友消息删除处理失败' . $ex->getMessage());
                    }

                }
            }
            return $this->Success(ErrorCode::ERROR, '好友消息删除处理成功');
        }

    }


    /**
     *发送到服务端回调
     * @param array $params
     * @return array
     */
    public function appMessageToService(array $params): array
    {
        $messageKey = $this->zScore('messageKey', $params['key']);
        if ($messageKey !== null) {
            $message = $this->hGet('message', $params['key']);
            if (!empty($message)) {
                $messageArr = json_decode($message, true);
                $messageInfo = $this->getMessageInfo(['id' => $messageArr['id']]);
                $messageInfo->is_send = 1;
                $result = $messageInfo->save();
                /*删除redis数据*/
                if ($result) {
                    $count = $this->zRem('messageKey', $params['key']);
                    if ($count > 0) {
                        $this->hDel('message', $params['key']);
                    }
                }
            }
            return $this->Success('服务端信息回调处理成功');
        } else {
            return $this->Error(ErrorCode::ERROR, '服务端信息键值为空');
        }

    }

    /**
     *加好友回调
     * @param array $params
     * @return array
     */
    public function appAddFriendCallBack($fd, array $params): array
    {
        ApplicationContext::getContainer()->get(CallBackRequest::class)->validated($params['data'], __FUNCTION__);
        $params_data = $params['data'];
        if ($params['result'] == 1) {
            Db::beginTransaction();
            try {
                $task_mobile = TaskMobile::where(['mobile' => $params_data['mobile'], 'numberStr' => $params_data['numberStr']])->first();
                if (!empty($task_mobile)) {
                    $task_mobile->callback = intval($params_data['callback']);
                    $task_mobile->status = ConstCode::USE_STATUS_SEND;
                    $task_mobile->send_time = time();
                    $task_mobile->save();
                }
                Db::commit();
                return $this->Success('添加好友回调处理成功');
            } catch (\Throwable $ex) {
                Db::rollBack();
                return $this->Error(ErrorCode::ERROR, '添加好友回调处理失败' . $ex->getMessage());
            }
        } else {
            return $this->Error(ErrorCode::ERROR, '添加好友执行失败_' . $params_data['callback']);
        }

    }


    /**
     *是否执行
     * @param array $params
     * @return array
     */
    public function appAddFriend($fd, array $params): array
    {
        ApplicationContext::getContainer()->get(CallBackRequest::class)->validated($params['data'], __FUNCTION__);
        $params_data = $params['data'];
        if ($params['result'] == 1) {
            Db::beginTransaction();
            try {
                $task_mobile = TaskMobile::where(['mobile' => $params_data['mobile'], 'numberStr' => $params_data['numberStr']])->first();
                if (!empty($task_mobile)) {
                    $task_mobile->status = ConstCode::USE_STATUS_SEND;
                    $task_mobile->send_time = time();
                    $task_mobile->save();
                }
                Db::commit();
                return $this->Success('接收设备执行回调成功');
            } catch (\Throwable $ex) {
                Db::rollBack();
                return $this->Error(ErrorCode::ERROR, '接收设备执行回调失败' . $ex->getMessage());
            }
        } else {
            return $this->Error(ErrorCode::ERROR, '接收设备执行回调失败');
        }


    }


}